<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * LBL业务
 *
 */
class Tz extends Backend
{
    /**
     * Tz模型对象
     * @var \app\admin\model\Tz
     */
    protected $model = null;
    protected $bill=null;
    protected $conloadplan=null;
    protected $quickSearchField = ['TZID'];

    protected $defaultSortField = 'TZID,desc';

    protected $preExcludeFields = [''];
    protected $noNeedLogin      = ['*'];
    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Tz;
        $this->bill = new \app\admin\model\Bill();
        $this->conloadplan=new \app\admin\model\Conloadplan();
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();


        $wheres='';
        if(empty($where)){
            $wheres="OVERSTATUS=0";
        }
        $res = $this->model
            ->field(" *,dbo.f_get_billstatus(tzid) as status/*费用*/ , dbo.f_getsizetype(tzid) as sizetype, /*箱型*/

  dbo.f_getcntr(tz.tzid) as cntrno, /*箱号*/

(select top 1 PACKERDESC from CONLOADPLAN where tzid=tz.tzid) as PACKERDESC,

(select top 1 PACKERDATE from CONLOADPLAN where tzid=tz.tzid) as PACKERDATE,

(select top 1 FREESTORAGEFROM from CONLOADPLAN where tzid=tz.tzid) as FREESTORAGEFROM,

(select top 1 FREESTORAGETO from CONLOADPLAN where tzid=tz.tzid) as FREESTORAGETO,

(select top 1 HCDATE from CONLOADPLAN where tzid=tz.tzid) as HCDATE,

(select top 1 TXPLACE from CONLOADPLAN where tzid=tz.tzid) as TXPLACE,

(select top 1 SHPLACE from CONLOADPLAN where tzid=tz.tzid)  as SHPLACE,

(select top 1 HCPLACE from CONLOADPLAN where tzid=tz.tzid)  as HCPLACE,

(select top 1 TRUCKCORP from CONLOADPLAN where tzid=tz.tzid) as TRUCKCORP")
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where($wheres)
            ->where("exists ( select * from x_bjheadczy where x_bjheadczy.bjno=tz.bookingno and tz.OP=x_bjheadczy.czy)")
            ->order($order)
//            ->fetchSql()->select();
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $adminInfo          = $this->auth->getInfo();
            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $data['TZID']=$this->getmaxno($adminInfo['department'].'LBL');
//            $data['TZID']=date('Y',time()).$adminInfo['department'].'LBL'.time();;
            $data['OP']=$adminInfo['nickname'];
            $data['OPTIME']=date('Y-m-d H:i:s',time());
            $data['OPDEPT']=$adminInfo['department'];
            if($data['OVERSTATUS']==1){
                $data['OVEROP']=$adminInfo['nickname'];
                $data['OVERTIME']=date('Y-m-d H:i:s',time());
            }
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'),['id'=>$this->model->TZID]);
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->with('col')->find($id);
//        if($row['OVERSTATUS']==1){
//            $this->error('已提交不能修改');
//        }
        $row['OVERSTATUSS']=$row['OVERSTATUS'];
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }
//        $query= Db::query("select top 1 PACKERDESC,PACKERDATE,FREESTORAGEFROM,FREESTORAGETO,HCDATE,TXPLACE,SHPLACE,HCPLACE,TRUCKCORP from CONLOADPLAN,TZ where CONLOADPLAN.TZID=TZ.TZID and TZ.TZID='$id'");
//        $query= Db::query("select top 1  PACKERDESC,PACKERDATE,FREESTORAGEFROM,FREESTORAGETO,HCDATE,TXPLACE,SHPLACE,HCPLACE,TRUCKCORP from conloadplan as CONLOADPLAN, tz as TZ  where CONLOADPLAN.TZID=TZ.TZID and TZ.TZID='$id' ");
//        array_merge(Get_object_vars ($row),Get_object_vars ($query));
        $this->success('', [
            'row' => $row,
//            'query'=>$query
        ]);
    }

    /**
     * 删除
     * @param array $ids
     */
    public function del(array $ids = [])
    {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
        }

        $pk    = $this->model->getPk();
        $data  = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($data as $v) {
                if($v['OVERSTATUS']==1) {
                    Db::rollback();
                    $this->error('已提交不能删除');
                }
               $b_c= $this->bill->where('TZID',$v['TZID'])->count();
               $c=$this->conloadplan->where('TZID',$v['TZID'])->count();
               if($c>0 || $b_c>0){
                   Db::rollback(); $this->error('已生成费用 或者 已有做箱计划的不可以删除');
               }
                $count += $v->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }


    /**
     * 揽货员
     */
    public function sale(){
        $da=Db::table('saler')->select();
        $this->success('',$da);
    }
    /**
     * 效验报价单号
     */
    public function bjno(){
        $bjno=$this->request->get('bjno');
//        $bjno='2023BJ0001';
        $adminInfo          = $this->auth->getInfo();
        $query= Db::query("select * from x_bjhead where corptype='客户' and bjno='$bjno' and bjstatus='1'");
        if(!$query){
            $this->error('该报价单号无效，请重新输入!');
        }
        if($query[0]['BJSTATUS']!=1){
            $this->error('报价单未接受');
        }
        $qx=Db::query("select * from x_bjheadczy where  x_bjheadczy.bjno='$bjno' and x_bjheadczy.czy='$adminInfo[nickname]'");
        if(!$qx){
            $this->error('该报价单号不属于该操作员，请重新输入！');
        }
        $da=Db::query("select corp,goodsid,goods,unno,goodskind,SALES from x_bjhead where bjno='$bjno'");
        $this->success('',$da);
    }
    public function all(){
        $sql=$this->request->get('sql');
        $da=Db::query("$sql");
        $this->success('',$da);
    }
    /**
     * 费用审核界面
     */
    public function indexs(){
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $m='';
        foreach ($where as $k=>$item) {

            if ($item[0] == 'bill.statuss') {
                    $m="dbo.f_getflowstatus(BJNO) != '$item[2]'";
                unset($where[$k]);
            }
        }
        $adminInfo          = $this->auth->getInfo();
        $wheres='';
        if(empty($where)){
            $wheres=" overstatus='1' and  dbo.f_get_billstatus(tzid)='待审'";
//            $wheres="overstatus='1' ";
        }
        $res = $this->model
            ->field('*,dbo.f_get_billstatus(tzid) as statuss')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where(" checker='$adminInfo[nickname]'")
            ->where($wheres)
            ->where($m)
            ->order($order)
//            ->fetchSql()->select();
            ->paginate($limit);
//var_dump($res);die;
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 应收付对账单列表
     */
    public function index_dz(){
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $adminInfo          = $this->auth->getInfo();
        $type=$this->request->get('type');
//        $type=0;
        if($type==0){
            $wheres='BILL.BILLTYPE=0';
        }else{
            $wheres='BILL.BILLTYPE=1';
        }
//        $where[1]=['bill.BILLCLASS','=','正常&代垫'];
//        $where[2]=['tz.MONEYTYPE','=','RMB'];

        //把搜索条件按表分组
        foreach ($where as $k=>$item) {
            if ($item[0] == 'tz.BILLCLASS'){
                if ($item[2] == '更正') {
                    $wheres .= ' and BILL.BILLCLASS=2';
                } elseif ($item[2] == '正常&代垫') {
                    $wheres .= ' and BILL.BILLCLASS!=2';
                }
                 unset($where[$k]);
             }
            if ($item[0] == 'tz.BILLSTATUS') {
                if ($item[2] == '未对账') {
                    $wheres .= " and BILL.MARKNO is null ";
                } elseif($item[2] == '已对账') {
                    $wheres .= " and BILL.MARKNO is not null ";
                }
                unset($where[$k]);
            }

        }
        //获取第二层的条件
        $array=['tz.CORPCODE','tz.MONEYTYPE','tz.ITEMCODE','tz.TAXRATE','tz.JOBNO','tz.MARKNO'];
        $two_where=[];
        foreach ($where as $k=>$item) {
            if(in_array($item[0],$array)){
                $two_where[]=['bill.'.substr( $item[0],strripos( $item[0],".")+1),$item[1],$item[2]];
                unset($where[$k]);
            }
        }
        //查询第一层
        $res = $this->model
            ->field("tz.TZID,
	tz.SENDER,
	tz.GOODSC,
	goods.ENAME,
	conloadplan.CNTRNO,
	tz.PORTLOAD,
	tz.PORTDIS,
	SUM(CASE WHEN BILL.MONEYTYPE='RMB' THEN BILL.MONEY ELSE 0 END) AS RMB,
	SUM(CASE WHEN BILL.MONEYTYPE='USD' THEN BILL.MONEY ELSE 0 END) AS USD,
	conloadplan.ZHDATE,
	conloadplan.SHDATE,
	tz.SALER,
	tz.SALERDEPT,
	tz.OP,
	tz.OPDEPT,
	tz.OPTIME")
            ->join('bill BILL','tz.TZID=BILL.TZID')
            ->join('conloadplan','tz.TZID=conloadplan.TZID')
            ->join('goods','tz.CONTRACTNO=goods.GOODSID')
            ->alias($alias)
            ->where($wheres)
            ->where($two_where)
            ->where($where)
            ->order($order)
            ->group("tz.TZID, 
	tz.SENDER,
	tz.GOODSC,
	goods.ENAME,
	conloadplan.CNTRNO,
	tz.PORTLOAD,
	tz.PORTDIS,	
	conloadplan.ZHDATE,
	conloadplan.SHDATE,
	tz.SALER,
	tz.SALERDEPT,
	tz.OP,
	tz.OPDEPT,
	tz.OPTIME")
//            ->fetchSql()->select();
            ->paginate($limit);
//        var_dump($res);die;

        if(!empty($res->items())){

            $tzid=array_column($res->items(),'TZID');
            //获取第二层的条件
//            $one_where=[];
//            $two_where=[];
//            foreach ($where as $item) {
//                if(strpos($item[0],'bill') !== false){
//                    $two_where[]=$item;
//                }
//            }

            //查询第二层
            $two = $this->bill
                ->field("BILL.MARKNO,BILL.TZID,BILL.BILLID,BILL.BILLCLASS,
        BILL.JOBNO,
        BILL.CORPCODE,
        BILL.ITEMCODE,
        BILL.MONEYTYPE,
        BILL.MONEY,
        BILL.TAXRATE,
        BILL.AMOUNT,
        BILL.PRICETYPE,
        BILL.RATIO,
        BILL.MONEY * BILL.RATE AS ZHRMB,
        (SELECT DZOP FROM dzd WHERE dzd.DZDNO=BILL.MARKNO) AS DZOP,
        (SELECT DZDATE FROM dzd WHERE dzd.DZDNO=BILL.MARKNO) AS DZDATE,
        (SELECT JOBOP FROM dzd WHERE dzd.DZDNO=BILL.MARKNO) AS JOBOP,
        (SELECT JOBDATE FROM dzd WHERE dzd.DZDNO=BILL.MARKNO) AS JOBDATE")
                ->join('codelib CODELIB','BILL.ITEMCODE=CODELIB.CODE')
                ->alias('BILL')
                ->where($wheres)
                ->where($two_where)
                ->where('BILL.TZID','in',$tzid)
                ->where("CODELIB.CODETYPE='itemcode'")
                ->order($order)
//            ->fetchSql()->select();
                ->select();
//            var_dump($two);die;
        }
        $list=$res->toArray();
        foreach ($list['data'] as $k=>$item) {
            foreach ($two as $t) {
                if($item['TZID']==$t['TZID']){
                    $list['data'][$k]['two'][]=$t;
                }
            }
       }
        $this->success('', [
            'list'   => $list['data'],
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

}